package com.hcc.flow.server.service.flowTask;

import java.util.Arrays;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hcc.flow.server.common.advice.RRException;
import com.hcc.flow.server.common.enums.CheckStatusType;
import com.hcc.flow.server.common.enums.MsgType;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.dao.flowDesign.FlowTaskTypeDao;
import com.hcc.flow.server.dao.flowTask.CustomerDao;
import com.hcc.flow.server.dao.sys.OrgDao;
import com.hcc.flow.server.dao.sys.UserDao;
import com.hcc.flow.server.dto.flowTask.CustomerDto;
import com.hcc.flow.server.dto.workbench.MsgNoticeDto;
import com.hcc.flow.server.model.common.LoginUser;
import com.hcc.flow.server.model.flowDesign.FlowTaskType;
import com.hcc.flow.server.model.flowTask.Customer;
import com.hcc.flow.server.model.sys.Org;
import com.hcc.flow.server.model.sys.SysAuditLogs;
import com.hcc.flow.server.model.sys.SysUser;
import com.hcc.flow.server.service.sys.SysLogService;
import com.hcc.flow.server.service.workbench.MsgNoticeService;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.flowTask.CustomerVO;



@Service
public class AdCustomerService {
	@Autowired
	private CustomerDao customerDao;
	@Autowired
	private OrgDao orgDao;
	@Autowired
	private UserDao userDao;

	@Autowired
	private SysLogService logService;
	@Autowired
	private MsgNoticeService msgNoticeService;
	@Autowired
	private FlowTaskTypeDao flowTaskTypeDao;
	
	@Transactional
	public ApiResult<?> deleteEditStatus(String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("ID不能为空");
		}
		CustomerVO customer = customerDao.getById(id);
		if (customer == null) {
			return ApiResult.error("要删除的数据不存在");
		} else if (customer.getStatus() != null
				&& CheckStatusType.AUDITED.getCode().equals(customer.getStatus().toString())) {
			return ApiResult.error("已核准通过（审核通过）的数据不能删除");
		}
		customerDao.updateStatus(Arrays.asList(id), CheckStatusType.DELETE.getCode());
		logService.saveAuditLogs(new SysAuditLogs(UserUtil.getLoginUser().getUserId(), new Date(),"客户-逻辑删除", id));
		FlowTaskType flowTaskType= flowTaskTypeDao.getByModel(Customer.class.getSimpleName());
		if(flowTaskType == null){
			return ApiResult.error("通过类型实体名("+Customer.class.getSimpleName()+")未找到对应流程业务类型");
		}
		MsgNoticeDto notice = new MsgNoticeDto();
		notice.setType(MsgType.RESULT.getCode());
		notice.setTaskType(flowTaskType.getTaskTypeId().toString());
		notice.setTitle("客户被删除通知");
		notice.setCollectUserIds(Arrays.asList(customer.getCreateUserId(),customer.getFollowUserId()));//接收人
		StringBuffer sb = new StringBuffer().append("您录入/归属的客户已被删除,<br/>")
				.append("客户ID: ").append(customer.getIndexId()).append(",<br/>")
				.append("客户名称: ").append(customer.getCompanyName());
		
		notice.setContent(sb.toString());
		notice.setFlowFromId(id);
		notice.setFlowVerifyStatus(CheckStatusType.DELETE.getCode());
		notice.setFlowVerifyReason("客户被删除");
		ApiResult<?> apiResult = msgNoticeService.save(notice);
		if(!apiResult.isSuccess()){
			throw new RRException(apiResult.getMsg());
		}
		return apiResult;
	}
	
	@Transactional
	public ApiResult<?> editStatusSub(String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("ID不能为空");
		}
		CustomerVO local = customerDao.getById(id);
		if(local == null){
			return ApiResult.error("要提交的客户数据为不存在");
		}
		LoginUser loginUser = UserUtil.getLoginUser();
		Org org = orgDao.getById(loginUser.getOrgId());
		if(org == null){
			return ApiResult.error("未找到登录用户机构信息");
		}
		String ownAudit = "1";//自有审核模式: 0单一审核模式 1工作流审核模式
		if(StringUtilsV2.isBlank(ownAudit)){
			return ApiResult.error("登录用户机构自有审核模式未设置");
		}
		Customer customer = new Customer();
		customer.setCustomerId(id);
		customer.setStatus(CommUtil.null2Int(CheckStatusType.WAIT_AUDITED.getCode()));
		customer.setSubmitterId(loginUser.getUserId());
		customerDao.update(customer);
		ApiResult<?> apiResult = null;
		if("1".equals(ownAudit)){
			FlowTaskType flowTaskType= flowTaskTypeDao.getByModel(Customer.class.getSimpleName());
			if(flowTaskType == null){
				return ApiResult.error("通过类型实体名("+Customer.class.getSimpleName()+")未找到对应流程业务类型");
			}
			MsgNoticeDto notice = new MsgNoticeDto();
			notice.setType(MsgType.TASK.getCode());
			notice.setTaskType(flowTaskType.getTaskTypeId().toString());
			notice.setTitle("客户待(初)审通知");
			StringBuffer sb = new StringBuffer().append("需要您(初)审的")
					.append("客户ID: ").append(local.getIndexId()).append(",<br/>")
					.append("客户名称: ").append(local.getCompanyName());
			notice.setContent(sb.toString());
			notice.setFlowFromId(id);
			notice.setFlowVerifyStatus(CheckStatusType.WAIT_AUDITED.getCode());
			notice.setFlowVerifyReason("提交客户(初)审流程");
			notice.setFlowSubmitNo(String.valueOf(System.currentTimeMillis()));
			notice.setFlowOrgId(local.getCreateOrgId());
			apiResult = msgNoticeService.save(notice);
			if(!apiResult.isSuccess()){
				throw new RRException(apiResult.getMsg());
			}
		}
		logService.saveAuditLogs(new SysAuditLogs(loginUser.getUserId(), new Date(),"客户-提交(初)审流程"+(apiResult!=null?apiResult.getData():""), id));
		return ApiResult.ok();
	}
	
	
	@Transactional
	public ApiResult<?> save(CustomerDto customer) {
		if (customer == null) {
			return ApiResult.error("新增数据不能为空");
		} 
		if (StringUtilsV2.isBlank(customer.getCompanyName())) {
			return ApiResult.error("名称不能为空");
		} 
		if(StringUtilsV2.isBlank(customer.getCreditCode())){
			return ApiResult.error("统一社会信用代码不能为空");
		}

		if(customer.getBusinessTermBegin() != null && customer.getBusinessTermEnd() != null && customer.getBusinessTermBegin().compareTo(customer.getBusinessTermEnd()) == 1){
			return ApiResult.error("营业期限开始时间不能大于结束时间");
		}
		Customer localCustomer = customerDao.getByCreditCode(customer.getCreditCode());
		if(localCustomer != null){
			return ApiResult.error("统一社会信用代码已存在,对应客户:"+localCustomer.getCompanyName());
		}
		LoginUser loginUser = UserUtil.getLoginUser();
		Org loginOrg = orgDao.getById(loginUser.getOrgId());
		if(loginOrg == null){
			return ApiResult.error("未找到登录用户机构信息");
		}
		String ownAudit = "1";//自有审核模式: 0单一审核模式 1工作流审核模式
		if(StringUtilsV2.isBlank(ownAudit)){
			return ApiResult.error("登录用户机构自有审核模式未设置");
		}

		customer.setCreateUserId(loginUser.getUserId());
		customer.setCreateOrgId(loginUser.getOrgId());
		if(customer.getStatus() == null){
			customer.setStatus(CommUtil.null2Int(CheckStatusType.SUBMIT.getCode()));
		}else if(customer.getStatus() == CommUtil.null2Int(CheckStatusType.WAIT_AUDITED.getCode())){
			customer.setSubmitterId(loginUser.getUserId());
		}
		if(StringUtilsV2.isNotBlank(customer.getFollowUserId())){
			SysUser user = userDao.getUserById(customer.getFollowUserId());
			if(user != null){
				customer.setFollowOrgId(user.getOrgId());
				customer.setFollowUserId(user.getUserId());
			}
		}
		customerDao.save(customer);
		logService.saveAuditLogs(new SysAuditLogs(loginUser.getUserId(), new Date(),"客户-保存(入库)", customer.getCustomerId()));
		if(customer.getStatus() != null && customer.getStatus() == CommUtil.null2Int(CheckStatusType.WAIT_AUDITED.getCode())){
			ApiResult<?> apiResult = null;
			if("1".equals(ownAudit)){
				FlowTaskType flowTaskType= flowTaskTypeDao.getByModel(Customer.class.getSimpleName());
				if(flowTaskType == null){
					return ApiResult.error("通过类型实体名("+Customer.class.getSimpleName()+")未找到对应流程业务类型");
				}
				Customer dbCustomer = customerDao.getJcById(customer.getCustomerId());
				MsgNoticeDto notice = new MsgNoticeDto();
				notice.setType(MsgType.TASK.getCode());
				notice.setTaskType(flowTaskType.getTaskTypeId().toString());
				notice.setTitle("客户待(初)审通知");
				StringBuffer sb = new StringBuffer().append("需要您(初)审的")
						.append("客户ID: ").append(dbCustomer.getIndexId()).append(",<br/>")
						.append("客户名称: ").append(customer.getCompanyName());
				notice.setContent(sb.toString());
				notice.setFlowFromId(customer.getCustomerId());
				notice.setFlowVerifyStatus(CheckStatusType.WAIT_AUDITED.getCode());
				notice.setFlowVerifyReason("提交客户待(初)审流程");
				notice.setFlowSubmitNo(String.valueOf(System.currentTimeMillis()));
				apiResult = msgNoticeService.save(notice);
				if(!apiResult.isSuccess()){
					throw new RRException(apiResult.getMsg());
				}
			}
			logService.saveAuditLogs(new SysAuditLogs(loginUser.getUserId(), CommUtil.getDateJJSecond(new Date(), 1),"客户-提交(初)审"+(apiResult!=null?apiResult.getData():""), customer.getCustomerId()));
		}
		
		return ApiResult.ok();
	}
	
	
	@Transactional
	public ApiResult<?> update(CustomerDto customer) {
		if (customer == null) {
			return ApiResult.error("修改数据不能为空");
		}
		if (StringUtilsV2.isBlank(customer.getCustomerId())) {
			return ApiResult.error("要修改的客户ID不能为空");
		}
		CustomerVO localCustomer = customerDao.getById(customer.getCustomerId());
		if(localCustomer == null){
			return ApiResult.error("要修改的客户数据不存在");
		}
		if(localCustomer.getStatus().intValue() == 2){
			return ApiResult.error("审核中的客户不能被修改,请等待当次审核完成");
		}
		if(StringUtilsV2.isBlank(customer.getCreditCode()) && StringUtilsV2.isBlank(localCustomer.getCreditCode())){
			return ApiResult.error("统一社会信用代码不能为空");
		}

		if(customer.getBusinessTermBegin() != null && customer.getBusinessTermEnd() != null && customer.getBusinessTermBegin().compareTo(customer.getBusinessTermEnd()) == 1){
			return ApiResult.error("营业期限开始时间不能大于结束时间");
		}
		if(StringUtilsV2.isNotBlank(customer.getCreditCode())){
			Customer localCustomerCode = customerDao.getByCreditCode(customer.getCreditCode());
			if(localCustomerCode != null && !localCustomerCode.getCustomerId().equals(customer.getCustomerId())){
				return ApiResult.error("统一社会信用代码已存在,对应客户:"+localCustomerCode.getCompanyName());
			}
		}
		LoginUser loginUser = UserUtil.getLoginUser();
		Org loginOrg = orgDao.getById(loginUser.getOrgId());
		if(loginOrg == null){
			return ApiResult.error("未找到登录用户机构信息");
		}
		String ownAudit = "1";//自有审核模式: 0单一审核模式 1工作流审核模式
		if(StringUtilsV2.isBlank(ownAudit)){
			return ApiResult.error("登录用户机构自有审核模式未设置");
		}
		if(customer.getStatus() == null){
			customer.setStatus(CommUtil.null2Int(CheckStatusType.SUBMIT.getCode()));
		}else if(customer.getStatus().intValue() == CommUtil.null2Int(CheckStatusType.WAIT_AUDITED.getCode())){
			customer.setSubmitterId(loginUser.getUserId());
		}
		customerDao.update(customer);
		logService.saveAuditLogs(new SysAuditLogs(loginUser.getUserId(), new Date(),"客户-更新客户信息", customer.getCustomerId()));
		if(customer.getStatus() != null && customer.getStatus() == CommUtil.null2Int(CheckStatusType.WAIT_AUDITED.getCode())){
			ApiResult<?> apiResult = null;
			if("1".equals(ownAudit)){
				FlowTaskType flowTaskType= flowTaskTypeDao.getByModel(Customer.class.getSimpleName());
				if(flowTaskType == null){
					return ApiResult.error("通过类型实体名("+Customer.class.getSimpleName()+")未找到对应流程业务类型");
				}
				msgNoticeService.delReadStatusByFromId(customer.getCustomerId());//将在流程中的任务消息通知屏蔽
				customer.setSubmitterId(loginUser.getUserId());
				MsgNoticeDto notice = new MsgNoticeDto();
				notice.setType(MsgType.TASK.getCode());
				notice.setTaskType(flowTaskType.getTaskTypeId().toString());
				notice.setTitle("客户信息被更新后待(初)审通知");
				StringBuffer sb = new StringBuffer().append("需要您(初)审的")
						.append("客户ID: ").append(localCustomer.getIndexId()).append(",<br/>")
						.append("客户名称: ").append(customer.getCompanyName());
				notice.setContent(sb.toString());
				notice.setFlowFromId(customer.getCustomerId());
				notice.setFlowVerifyStatus(CheckStatusType.WAIT_AUDITED.getCode());
				notice.setFlowVerifyReason("更新客户信息后提交客户(初)审流程");
				notice.setFlowSubmitNo(String.valueOf(System.currentTimeMillis()));
				notice.setFlowOrgId(localCustomer.getCreateOrgId());
				apiResult = msgNoticeService.save(notice);
				if(!apiResult.isSuccess()){
					throw new RRException(apiResult.getMsg());
				}
			}
			logService.saveAuditLogs(new SysAuditLogs(loginUser.getUserId(), CommUtil.getDateJJSecond(new Date(), 1),"客户-更新客户信息后提交(初)审流程"+(apiResult!=null?apiResult.getData():""), customer.getCustomerId()));
		}
		return ApiResult.ok();
	}

}
